package com.powernode.mybatis.utils;



import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;

import java.io.IOException;

/**
 * author 金宇廷的星空
 * version 1.0
 * date  2023/4/9 16:20
 * poject Mybatis
 */
public class SqlSessionUtil {
    private SqlSessionUtil() {
    }

    private static SqlSessionFactory sqlSessionFactory;

    static {
        try {
            sqlSessionFactory = new SqlSessionFactoryBuilder().build(Resources.getResourceAsStream("mybatis-config.xml"));
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    //全局的安全线程
    private static ThreadLocal <SqlSession>local = new ThreadLocal<>();

    public static SqlSession openSession() {

        SqlSession sqlSession = local.get();
        if (sqlSession == null) {
            sqlSession = sqlSessionFactory.openSession();
            //绑定当前线程，下次拿到的时候就直接返回就行
            local.set(sqlSession);
        }
        return sqlSession;
    }

    //解绑
    public static void close(SqlSession sqlSession){
        if (sqlSession!=null){
            //解除绑定，移除线程，TOMCAT支持线程池，防止下一次别人取到这个链接
            sqlSession.close();
            local.remove();
        }

    }
}


